/**
 * 关联知识点或辅助词
 */
import * as React from 'react';
import { connect } from 'react-redux';
import { get, find } from 'lodash';
import { Form, Button, message, Popover, Radio, Menu, Tabs } from 'antd';
import ReactCustomScrollBars from 'react-custom-scrollbars';

import { fetchKnowledgeList, fetchKnowledgeDetail } from 'actions/knowledge';
import { fetchAssistList, fetchAssistDetail } from 'actions/assist';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableSearch = LoadableComponent(() => import('pages/knowledge/searchForm'));
const LoadableCustomPagination = LoadableComponent(() =>
  import('components/common/CustomPagination')
);

const TabPane = Tabs.TabPane;

interface WordListProps {
  dispatch: (action: any) => any;
  onOk: (data: any) => any;
  onCancel: () => any;
  onVisibleChange: () => any;
  form: any;
  knowledgeList: any[];
  knowledgeTotal: number;
  assistList: any[];
  assistTotal: number;
  word: any;
}

interface WordListState {
  selectWordId: number;
  wordDetail: any;
  current: number;
  activeKey: string;
}
class WordList extends React.Component<WordListProps, WordListState> {
  static PAGESIZE = 20;

  static defaultProps: WordListProps = {
    dispatch: () => {},
    onOk: () => {},
    onCancel: () => {},
    onVisibleChange: () => {},
    form: null,
    knowledgeList: [],
    knowledgeTotal: 0,
    assistList: [],
    assistTotal: 0,
    word: {},
  };
  constructor(props: WordListProps) {
    super(props);

    const knowledgeId = get(props, 'word.knowledgeId', 0);
    const assistId = get(props, 'word.assistId', 0);

    this.state = {
      selectWordId: knowledgeId ? knowledgeId : assistId,
      wordDetail: null,
      current: 1,
      activeKey: knowledgeId ? 'knowledge' : 'assist',
    };
  }

  componentWillMount() {
    const { word } = this.props;

    if (word.assistId) {
      this.setState(
        {
          activeKey: 'assist',
        },
        () => {
          this.handleFetchWordList();
          this.handleFetchWordDetail(word.assistId);
        }
      );
    } else {
      this.handleFetchWordList();
      if (word.knowledgeId) {
        this.handleFetchWordDetail(word.knowledgeId);
      }
    }
  }

  handleFetchWordDetail(wordId: number) {
    const { activeKey } = this.state;
    const { dispatch } = this.props;

    const action =
      activeKey === 'knowledge' ? fetchKnowledgeDetail(wordId) : fetchAssistDetail(wordId);

    dispatch(action).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        this.setState({
          wordDetail: result.response.data,
        });
      }
    });
  }

  // 分页回调
  onPageChange = (page: number) => {
    const { activeKey } = this.state;
    this.setState({
      current: page,
    });
    this.handleFetchWordList({ page });
  };

  /**
   * 查询Knowledge|assist列表
   */
  handleFetchWordList = (params: any = {}, isSearch: boolean = false, callback: any = () => {}) => {
    const { current: page, activeKey } = this.state;
    const pageSize = WordList.PAGESIZE;

    params = { page, pageSize, ...params };
    if (isSearch) {
      params.page = 1;
    }

    const action = activeKey === 'knowledge' ? fetchKnowledgeList(params) : fetchAssistList(params);
    this.props.dispatch(action).then(callback);
  };

  handleSelectWord = (selectWordId: any = 0) => {
    this.setState(
      {
        selectWordId,
      },
      () => {
        this.handleFetchWordDetail(selectWordId);
      }
    );
  };

  // 提交关联方式
  handleParseSubmit = (e: any) => {
    e.preventDefault();

    const { onOk, form } = this.props;

    form.validateFields((error: any, values: Record<string, any>) => {
      if (error) return;

      const { type } = values;
      const { selectWordId, activeKey } = this.state;
      if (activeKey === 'knowledge') {
        onOk({ knowledgeId: selectWordId, type });
      } else {
        onOk({ assistId: selectWordId, type });
      }
    });
  };

  // 取消单词关联
  handleResetParse = () => {
    const { onOk } = this.props;
    onOk(null);
  };

  // 切换tab,重置分页,隐藏单词详情
  handleTabChange = (activeKey: string) => {
    this.setState(
      {
        activeKey,
        current: 1,
        selectWordId: 0,
      },
      () => {
        this.handleFetchWordList();
      }
    );
  };

  // 使用知识点的默认图片
  // 辅助词images => cover
  getDefaultImgUrl = () => {
    const { wordDetail } = this.state;

    // 辅助词或者辅助词没有设置封面
    const cover = get(wordDetail, 'cover', null);
    if (cover) {
      return cover.uri;
    }

    const images = get(wordDetail, 'images', []);
    const theDefault = find(images, ['isCover', true]);
    return theDefault ? theDefault.uri : get(wordDetail, 'images[0].uri', null);
  };

  renderWordDetail = () => {
    const { word, form } = this.props;
    const { getFieldDecorator } = form;
    const { wordDetail, selectWordId, activeKey } = this.state;
    const imgUrl = this.getDefaultImgUrl();

    const wordRelateId = word.knowledgeId ? word.knowledgeId : word.assistId ? word.assistId : 0;
    const type = wordRelateId === selectWordId && get(word, 'type', null);

    const radioStyle = {
      display: 'block',
      marginBottom: 6,
    };
    const content = !wordDetail ? (
      <p className="loading-placeholder">Loading...</p>
    ) : (
      <Form onSubmit={this.handleParseSubmit}>
        <Form.Item>
          {getFieldDecorator('type', {
            initialValue: type,
            rules: [
              {
                required: true,
                message: '请选择一种解释方式',
              },
            ],
          })(
            <Radio.Group>
              <Radio style={radioStyle} value={1}>
                {wordDetail.chinese}
              </Radio>
              {imgUrl && (
                <Radio style={radioStyle} value={0}>
                  <img
                    width="80"
                    height="80"
                    src={imgUrl}
                    style={{ border: '1px solid #efefef' }}
                  />
                </Radio>
              )}
            </Radio.Group>
          )}
        </Form.Item>
        <Form.Item>
          <Button onClick={this.handleResetParse}>取消关联</Button>
          &nbsp;&nbsp;&nbsp;
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
      </Form>
    );

    return (
      <Popover
        placement="left"
        content={content}
        title="选择单词解释"
        visible={selectWordId > 0}
        autoAdjustOverflow={true}
      />
    );
  };

  // 根据Tab渲染word
  renderWordItems = () => {
    const { knowledgeList, assistList } = this.props;
    const { selectWordId, activeKey } = this.state;
    const wordList = activeKey === 'knowledge' ? knowledgeList : assistList;

    let menuItems = null;
    if (wordList.length) {
      menuItems = (
        <Menu
          mode="inline"
          onSelect={(item: any) => {
            this.handleSelectWord(item['key']);
          }}
          selectedKeys={[String(selectWordId)]}>
          {wordList.map((item: any) => {
            const { id, name, partOfSpeech, chinese } = item;
            return (
              <Menu.Item key={id}>
                {name} ({partOfSpeech} | {chinese})
              </Menu.Item>
            );
          })}
        </Menu>
      );
    } else {
      menuItems = (
        <p className="loading-placeholder">
          没有找到
          {activeKey === 'knowledge' ? '知识点' : '辅助词'}.
        </p>
      );
    }

    return menuItems;
  };

  render() {
    const { knowledgeTotal, assistTotal, onCancel } = this.props;
    const { current, activeKey } = this.state;
    const wordTotal = activeKey === 'knowledge' ? knowledgeTotal : assistTotal;

    const paginParams = {
      current,
      total: wordTotal,
      pageSize: WordList.PAGESIZE,
      onChange: this.onPageChange,
      simple: true,
      style: {
        float: 'none',
        textAlign: 'center',
      },
    };

    const content = (
      <ReactCustomScrollBars
        autoHide={true}
        autoHeight={true}
        autoHeightMin={700}
        autoHideTimeout={600}
        autoHideDuration={400}>
        <LoadableSearch
          showAddButton={false}
          handleCreate={() => {}}
          handleSearch={this.handleFetchWordList}
        />
        <div>{this.renderWordItems()}</div>
        <LoadableCustomPagination {...paginParams} />
      </ReactCustomScrollBars>
    );

    return (
      <>
        <div
          onClick={(e: any) => {
            e.stopPropagation();
            onCancel();
          }}
          style={{
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            position: 'fixed',
            backgroundColor: '#000',
            opacity: 0.3,
            zIndex: 2,
          }}
        />
        <Popover
          overlayStyle={{ width: '360px' }}
          trigger="click"
          placement="right"
          title={
            <div>
              <Tabs defaultActiveKey={activeKey} onChange={this.handleTabChange}>
                <TabPane tab="知识点" key="knowledge">
                  {content}
                </TabPane>
                <TabPane tab="辅助词" key="assist">
                  {content}
                </TabPane>
              </Tabs>
            </div>
          }
          visible={true}
          autoAdjustOverflow={true}>
          {this.renderWordDetail()}
        </Popover>
      </>
    );
  }
}

interface OwnProps {
  onOk: (data: any) => any;
  onCancel: () => any;
  word: any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { knowledgeTotal, knowledgeList } = state.knowledge;
  const { assistTotal, assistList } = state.assist;
  const { onOk, onCancel, word } = ownProps;

  return {
    knowledgeTotal,
    knowledgeList,
    assistTotal,
    assistList,
    word,
    onOk,
    onCancel,
  };
}

export default connect(mapStateToProps)(Form.create()(WordList));
